<template>
  <view class="flex-col page group">
    <!-- Page 1 -->
    <view class="page" v-if="pageId == 0">
      <view class="flex-col section_card">
        <view class="flex-row items-center">
          <image class="icon_explain" src="/static/icon/notice_pink.svg" />
          <text class="font_explain ml-5">说明：</text>
        </view>
        <text class="font mt-7">
          感谢您完成本次内在能力方面的评估问卷，以下是您在认知、运动、营养、视力、听力、心理状况维度的详细结果。
        </text>
      </view>
      <view class="flex-col section_card view_2 mt-8">
        <echarts :option="option" height="500rpx"></echarts>
        <view class="mt-4 flex-col">
          <uni-collapse>
            <uni-collapse-item class="font-explain" v-for="(item, index) in results" :key="index">
              <template v-slot:title>
                <view class="flex-row items-center collapse-title">
                  <image class="image_9" :src="item.iconUrl" />
                  <text class="font_explain ml-7">{{ item.title }} ({{ roundedScore(item.total) }}/100)</text>
                </view>
              </template>
              <view class="submodule-wrapper">
                <view class="flex-row justify-between submodule" v-for="(subitem, index) in submodules(item)"
                  :key="index">
                  <text class="font_explain ml-7">· {{ subitem.title }}</text>
                  <text class="font">{{ subitem.content }}</text>
                </view>
              </view>
            </uni-collapse-item>
          </uni-collapse>
        </view>
      </view>
      <view class="flex-row mt-16">
        <button class="button half-button" hover-class="button-hover" @click="toHome">
          返回主页
        </button>
        <button class="button half-button ml-10" hover-class="button-hover" @click="toNextPage">
          下一页
        </button>
      </view>
    </view>
    <!-- Page 2 -->
    <view class="page" v-if="pageId == 1">
      <view class="flex-col section_card">
        <view class="flex-row items-center">
          <image class="icon_explain" src="/static/icon/notice_pink.svg" />
          <text class="font_explain ml-5">说明：</text>
        </view>
        <text class="font mt-7">
          根据上述评测，我们为您提供了一些建议和指导，帮助您更好地管理和改善您的健康状况。
        </text>
      </view>
      <view class="flex-col section_card view_2 mt-8">
        <view class="flex-col">
          <uni-collapse>
            <uni-collapse-item class="font-explain" v-for="(item, key) in results" :key="key">
              <template v-slot:title>
                <view class="flex-row items-center collapse-title">
                  <image class="image_9" :src="item.iconUrl" />
                  <text class="font_explain ml-7">{{ item.title }}</text>
                </view>
              </template>
              <view class="submodule-wrapper">
                <text class="font-advice" user-select>{{ advices[key] ? advices[key].advices : '' }}</text>
              </view>
            </uni-collapse-item>
          </uni-collapse>
        </view>
      </view>
      <view class="flex-row mt-16">
        <button class="button half-button" hover-class="button-hover" @click="toPrevPage">
          上一页
        </button>
        <button class="button half-button ml-10" hover-class="button-hover" @click="toHome">
          返回主页
        </button>
      </view>
    </view>
  </view>
</template>

<script>
import echarts from "../../components/Questionnare/echarts/echarts.vue";
import { assessKeys, getCompressor, getAdvicesFromAssessmentResults } from "../../util/questionnaire/index.js";
export default {
  components: {
    echarts,
  },
  data() {
    return {
      option: {},
      results: {},
      advices: {},
      pageId: 0,
    };
  },

  async mounted() {
    this.pageId = 0;
    console.log("assess_result mounted");
    let results = null;
    try {
      // try to get from remote
      const res = await this.$request({
        url: "/survey/get/",
        method: "GET",
        data: {
          type: "assessment",
        },
      });
      if (res && res.data && res.data.result) {
        results = res.data.result;
      } else {
        throw "get assess results failed";
      }
    } catch (e) {
      console.log(e);
      this.$tabbar.switchTab({
        url: "/pages/test/test",
      })
      return;
    }

    console.log("get assess results: ", results);
    // decompress
    const compressor = getCompressor('assessment');
    this.results = compressor.decompress(results.result);
    console.log("decompress results: ", this.results);

    // 获取建议信息
    this.advices = getAdvicesFromAssessmentResults(this.results);
    console.log("advices: ", this.advices);

    const values = [];
    for (const key of assessKeys) {
      values.push(this.roundedScore(this.results[key].total));
    }
    console.log("scores computed: ", values);

    this.option = {
      radar: {
        shape: "circle",
        indicator: [
          { name: "认知", max: 100 },
          { name: "运动", max: 100 },
          { name: "活力", max: 100 },
          { name: "视力", max: 100 },
          { name: "听力", max: 100 },
          { name: "心理", max: 100 },
        ],
        axisTick: {
          length: 10,
        },
        splitNumber: 3,
        splitArea: {
          areaStyle: {
            color: ["#f4ae82", "#fdcaaa", "#ffe2cf"],
            shadowColor: "rgba(0, 0, 0, 0.2)",
            shadowBlur: 10,
          },
        },
      },
      axisLine: {
        lineStyle: {
          color: "rgba(211, 253, 250, 0.8)",
        },
      },
      splitLine: {
        lineStyle: {
          color: "rgba(211, 253, 250, 0.8)",
        },
      },
      series: [
        {
          // name: "个人得分",
          type: "radar",
          data: [
            {
              value: values,
              name: "得分",
              label: {
                show: true,
                position: "top",
                distance: 8,
                fontWeight: "bold",
                color: "#99434B",
                // formatter: function (params) {
                //   return params.value === 1 ? "!风险" : "";
                // },
              },
            },
          ],
          itemStyle: {
            color: "#f06976",
          },
          lineStyle: {
            color: "#f06976",
          },
          areaStyle: {
            color: "rgba(255, 197, 203, 0.6)",
          },
          // selectedMode: "single",
          // select: {
          //   label: {
          //     show: true,
          //   },
          // },
        },
      ],
    };
  },

  methods: {
    toNextPage() {
      this.pageId = 1;
    },
    toPrevPage() {
      this.pageId = 0;
    },
    toHome() {
      this.$tabbar.switchTab({
        url: "/pages/test/test",
      })
    },
    roundedScore(total) {
      if (!total || typeof total.score !== 'number' || typeof total.max !== 'number') {
        return 0;
      }
      // 应用 reverse 逻辑：如果 reverse=true，实际分数 = max - 原始分数
      let actualScore = total.score;
      if (total.reverse) {
        actualScore = total.max - total.score;
      }
      return Math.round((actualScore / total.max) * 100);
    },
    submodules(item) {
      if (!item || !item.submodules) {
        return [];
      }
      const submodules = Object.values(item.submodules);
      return submodules;
    },
  },
};
</script>

<style>
page {
  background-color: #f5f5f5;
}
</style>

<style scoped lang="css">
.mt-7 {
  margin-top: 14rpx;
}

.ml-5 {
  margin-left: 10rpx;
}

.ml-7 {
  margin-left: 14rpx;
}

.font {
  font-size: 32rpx;
  color: #000000;
}

.group {
  padding: 24rpx 33rpx 0;
}

.section_card {
  padding: 16rpx 24rpx;
  background-color: #ffffff;
  border-radius: 24rpx;
}

.icon_explain {
  width: 48rpx;
  height: 48rpx;
}

.list {
  border-radius: 24rpx;
}

.list-item:first-child {
  margin-top: 0;
}

.image_9 {
  width: 56rpx;
  height: 56rpx;
}

.font_explain {
  font-size: 30rpx;
  font-weight: 700;
  color: #000000;
}

.button {
  margin-top: 30rpx;
  border-radius: 24rpx;
  background-color: #f26a77;
  color: #ffffff;
}

.button-hover {
  margin-top: 30rpx;
  border-radius: 24rpx;
  background-color: #ffc5cb;
  color: #ffffff;
}

.full-button {
  width: 680rpx;
}

.half-button {
  align-self: stretch;
  width: 640rpx;
}

.collapse-title {
  padding: 8rpx 0;
}

.submodule-wrapper {
  padding: 12rpx 0;
}

.submodule {
  margin-top: 8rpx;
}

.submodule:first-child {
  margin-top: 0;
}

.font-advice {
  font-size: 32rpx;
}
</style>